package com.example.film_b.service.impl;

import com.example.film_b.entity.Comment;
import com.example.film_b.entity.User;
import com.example.film_b.mapper.CommentMapper;
import com.example.film_b.mapper.MovieMapper;
import com.example.film_b.mapper.UserMapper;
import com.example.film_b.service.CommentService;
import com.example.film_b.service.UserLikeRedisService;
import com.example.film_b.service.UserLikeService;
import com.example.film_b.utils.FileUtil;
import com.example.film_b.utils.PicUrlUtil;
import com.example.film_b.vo.comment.CommentMovieVo;
import com.example.film_b.vo.comment.CommentStripVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaban.analysis.jieba.JiebaSegmenter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
// 添加数字格式化工具
import java.text.DecimalFormat;

/**
* @description 针对表【comment】的数据库操作Service实现
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserLikeRedisService userLikeRedisService;

    @Resource
    private UserLikeService userLikeService;

    @Resource
    private MovieMapper movieMapper;

    @Override
    public Integer addComment(Comment comment, String username) {
        // 获取当前登录用户的基本信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        Long uid = user.getId();
        String nickname = user.getNickname();
        comment.setUid(uid);
        comment.setType(0);
        comment.setAgree(0);
        comment.setNickname(nickname);
        // 设置当前时间
        comment.setTime(new Timestamp(System.currentTimeMillis()));

        Comment isCommentExists = commentMapper.selectOne(
                new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getUid, comment.getUid())
                        .eq(Comment::getMid, comment.getMid())
        );
        // 判断如果评价信息已经存在，则更新评论即可
        if (!Objects.isNull(isCommentExists)) {
            comment.setAgree(isCommentExists.getAgree());
            int update = commentMapper.update(comment,
                    new LambdaUpdateWrapper<Comment>()
                            .eq(Comment::getUid, comment.getUid())
                            .eq(Comment::getMid, comment.getMid()));
            if (update <= 0) {
                return -1;
            } else {
                // 添加评分更新调用
                this.updateMovieScore(comment.getMid());
                return 1;
            }
        }

        // 如果评价信息不存在，则插入评价信息
        int isInsert = commentMapper.insert(comment);
        if (isInsert > 0) {
            this.updateMovieScore(comment.getMid());
            return 2;
        }else{
            return -2;
        }
    }

    @Override
    public CommentStripVo getOwnComment(Long uid, Long mid) {
        CommentStripVo commentStripVo = commentMapper.selectOwnCommentByUidAndMid(uid, mid);
        if (!Objects.isNull(commentStripVo)) {
            commentStripVo.setAvatar(PicUrlUtil.getFullAvatarUrl(commentStripVo.getAvatar()));
        }
        return commentStripVo;
    }

    @Override
    public List<CommentStripVo> getMoreCommentsByMovieId(Long mid, int currentPage, int pageSize) {
        currentPage = currentPage * pageSize;
        List<CommentStripVo> commentStripVos = commentMapper.selectMoreCommentsByMovieId(mid, currentPage, pageSize);
        for (CommentStripVo comment: commentStripVos) {
            if (comment.getType() == 0) {
                comment.setAvatar(PicUrlUtil.getFullAvatarUrl(comment.getAvatar()));
            }
            // 更新点赞数：总点赞数 = 数据库中的点赞数 + redis中的点赞数
            comment.setAgree(comment.getAgree() + userLikeRedisService.getUserLikeCountFromRedis(comment.getId()));
        }
        return commentStripVos;
    }

    @Override
    public Map<String, Object> getMoreOwnCommentMovieMoments(Long uid, Integer currentPage, Integer pageSize) {
        Integer currentIndex = (currentPage - 1) * pageSize;
        List<CommentMovieVo> commentMovieVos = commentMapper.selectOwnCommentMovieMoments(uid, currentIndex, pageSize);
        for (CommentMovieVo commentMovieVo: commentMovieVos) {
            // 获取头像和电影海报完整的url
            String avatar = commentMovieVo.getCommentStripVo().getAvatar();
            commentMovieVo.getCommentStripVo().setAvatar(PicUrlUtil.getFullAvatarUrl(avatar));
            String pic = commentMovieVo.getMovieStripVo().getPic();
            commentMovieVo.getMovieStripVo().setPic(PicUrlUtil.getFullMoviePicUrl(pic));

            // 更新点赞数：总点赞数 = 数据库中的点赞数 + redis中的点赞数
            long cid = commentMovieVo.getCommentStripVo().getId();
            int dbAgree = commentMovieVo.getCommentStripVo().getAgree();
            int redisAgree = userLikeRedisService.getUserLikeCountFromRedis(cid);
            commentMovieVo.getCommentStripVo().setAgree(dbAgree + redisAgree);
        }
        for (CommentMovieVo moment: commentMovieVos) {
            // 获取用户点赞状态
            int status = userLikeService.getUserLikeStatus(moment.getCommentStripVo().getId(), uid);
            moment.getCommentStripVo().setStatus(status);
        }

        // 获取用户动态总条目数
        List<Comment> comments = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getUid, uid));
        Integer total = comments.size();

        Map<String, Object> page = new HashMap<>(2);
        page.put("total", total);
        page.put("records", commentMovieVos);
        return page;
    }

    @Override
    public int removeOwnComment(Long uid, Long mid) {
        // 先获取被删除评论的电影ID
        Comment comment = commentMapper.selectOne(
            new LambdaQueryWrapper<Comment>()
                .eq(Comment::getUid, uid)
                .eq(Comment::getMid, mid)
        );
        
        int result = commentMapper.delete(
            new LambdaQueryWrapper<Comment>()
                .eq(Comment::getUid, uid)
                .eq(Comment::getMid, mid));
        
        if (result > 0 && comment != null) {
            this.updateMovieScore(comment.getMid());
        }
        return result;
    }


    
    public void updateMovieScore(Long mid) {
        // 创建保留一位小数的格式器
        DecimalFormat df = new DecimalFormat("#0.0");
        
        Map<String, Object> stats = commentMapper.selectScoreStatsByMid(mid);
        
        if (stats == null || ((Number) stats.get("total")).intValue() == 0) {
            movieMapper.updateMovieScore(mid, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,0);
            return;
        }
    
        int total = ((Number) stats.get("total")).intValue();
    
        // 格式化每个星级百分比
        double five = Double.parseDouble(df.format(((Number) stats.get("five")).doubleValue() / total * 100));
        double four = Double.parseDouble(df.format(((Number) stats.get("four")).doubleValue() / total * 100));
        double three = Double.parseDouble(df.format(((Number) stats.get("three")).doubleValue() / total * 100));
        double two = Double.parseDouble(df.format(((Number) stats.get("two")).doubleValue() / total * 100));
        double one = Double.parseDouble(df.format(((Number) stats.get("one")).doubleValue() / total * 100));
    
        // 最终评分保留一位小数
        double score = (5*five + 4*four + 3*three + 2*two + 1*one) / 100 * 2;
        score = Double.parseDouble(df.format(score));
        
        movieMapper.updateMovieScore(mid, five, four, three, two, one, score,  total);
    }
}




